<template>
  <el-main v-loading="loading">
    <el-button type="primary" size="medium" @click="dialogFormVisible = true">添加用户</el-button>
    <el-button type="success" size="medium" @click="batchChgStatus(1)">批量启用</el-button>
    <el-button type="warning" size="medium" @click="batchChgStatus(0)">批量停用</el-button>
    <el-button type="danger" size="medium" @click="batchChgStatus(2)">批量删除</el-button>

    <el-dialog title="用户信息" width="26%" :visible.sync="dialogFormVisible">
      <el-form  :model="registInfo" status-icon :rules="rules" ref="registInfo" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="user.username">
          <el-input v-model="registInfo.user.username" @blur="checkUsername()"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="user.password">
          <el-input type="password" v-model="registInfo.user.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="user.nickname">
          <el-input v-model="registInfo.user.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="user.phone">
          <el-input v-model.number="registInfo.user.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="user.roleIDs">
          <el-checkbox-group v-model="registInfo.user.roleIDs">
            <el-checkbox-button label="1" @change="adminViewChg">管理员</el-checkbox-button>
            <el-checkbox-button label="2" @change="propertyViewChg">物业</el-checkbox-button>
            <el-checkbox-button label="3" @change="merchantViewChg">商家</el-checkbox-button>
            <el-checkbox-button label="4" @change="userViewChg">业主</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
        <span v-if="registInfo.user.roleIDs.includes('2')">
          <el-form-item label="小区名称" prop="community.name">
            <el-input v-model="registInfo.community.name"></el-input>
          </el-form-item>
          <el-form-item label="小区地址" prop="community.address">
            <el-input v-model="registInfo.community.address"></el-input>
          </el-form-item>
          <el-form-item label="小区介绍" prop="community.introduce">
            <el-input v-model="registInfo.community.introduce"></el-input>
          </el-form-item>
          <el-form-item label="管家电话" prop="community.helpPhone">
            <el-input v-model.number="registInfo.community.helpPhone"></el-input>
          </el-form-item>
        </span>
        <span v-if="registInfo.user.roleIDs.includes('3')">
          <el-form-item label="商家名称" prop="merchant.name">
            <el-input v-model="registInfo.merchant.name"></el-input>
          </el-form-item>
          <el-form-item label="商家介绍" prop="merchant.detail">
            <el-input v-model="registInfo.merchant.detail"></el-input>
          </el-form-item>
          <el-form-item label="营业执照" prop="merchant.charter">
            <el-upload
              name="files"
              class="upload-demo"
              action="http://localhost:8080/oos/upload/img/charter"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :limit="1"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1mb</div>
            </el-upload>
          </el-form-item>
        </span>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-table
      ref="multipleTable"
      :data="pageInfo.list"
      height="79vh"
      border
      tooltip-effect="dark"
      style="width: 100%; margin-top:20px;"
      @select-all="handleSelectAll"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55"
        align="center">
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="200"
        align="center">
      </el-table-column>
      <el-table-column
        prop="password"
        label="密码"
        width="400"
        align="center">
      </el-table-column>
      <el-table-column
        prop="nickname"
        label="昵称"
        width="180"
        align="center">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        width="160"
        align="center">
      </el-table-column>
      <!-- 从账户拥有的所有角色中循环判断每一个角色名称，拥有哪个，显示哪个 -->
      <el-table-column
        label="角色"
        :filters="[{text: '业主', value: 4}, {text: '商家', value: 3}, {text: '物业', value: 2}, {text: '管理员', value: 1}]"
        :filter-method="filterRoleTag"
        filter-placement="bottom-end"
        width="260"
        align="center">
        <template slot-scope="scope">
          <span v-for="(role,index) in scope.row.roles" :key="index">
            <el-tag type="info" v-if="role.id == 1">管理员</el-tag>
            <el-tag v-if="role.id == 2">物业</el-tag>
            <el-tag type="warning" v-if="role.id == 3">商家</el-tag>
            <el-tag type="success" v-if="role.id == 4">业主</el-tag>
          </span>
        </template>
      </el-table-column>
      <!-- 根据账户状态显示不同标签 1启用 0停用 2删除 --> 
      <el-table-column
        label="状态"
        :filters="[{text: '已启用', value: 1}, {text: '已停用', value: 0}, {text: '已删除', value: 2}]"
        :filter-method="filterStatusTag"
        filter-placement="bottom-end"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 1">已启用</el-tag>
          <el-tag type="warning" v-if="scope.row.status == 0">已停用</el-tag>
          <el-tag type="danger" v-if="scope.row.status == 2">已删除</el-tag>
        </template>
      </el-table-column>
      <!-- 启用/停用账号，当账号是删除状态时不显示此项 -->
      <el-table-column
        label="是否启用"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            @click.native.prevent="chgStatus(scope.row, scope.row.status)"
            :active-value=1
            :inactive-value=0
            v-if="!(scope.row.status == 2)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        show-overflow-tooltip
        align="center">
        <!-- 恢复账号按钮 -->
        <template slot-scope="scope">
          <el-popconfirm
            confirm-button-text='好的'
            cancel-button-text='不用了'
            icon="el-icon-info"
            icon-color="red"
            title="确定恢复这个账号吗？"
            @confirm="chgStatus(scope.row, 1)"
            v-if="scope.row.status == 2">
            <el-button type="text" slot="reference" size="small">恢复账号</el-button>
          </el-popconfirm>
          <!-- 非被删除账号的分配角色与删除按钮 -->
          
          <span v-else>
            <el-popover
              placement="bottom"
              width="292"
              trigger="click">
              <el-button type="text" slot="reference" size="small">分配角色</el-button>
              <el-checkbox-group v-model="scope.row.roleIDs" :min="1">
                <el-checkbox-button label="1" :checked="checkRole(scope.row.roles, 1)" @change="chgRole(scope.row, 1)">
                  管理员
                </el-checkbox-button>
                <el-checkbox-button label="2" :checked="checkRole(scope.row.roles, 2)" @change="chgRole(scope.row, 2)">
                  物业
                </el-checkbox-button>
                <el-checkbox-button label="3" :checked="checkRole(scope.row.roles, 3)" @change="chgRole(scope.row, 3)">
                  商家
                </el-checkbox-button>
                <el-checkbox-button label="4" :checked="checkRole(scope.row.roles, 4)" @change="chgRole(scope.row, 4)">
                  业主
                </el-checkbox-button>
              </el-checkbox-group>
            </el-popover>
            <el-popconfirm
              confirm-button-text='好的'
              cancel-button-text='不用了'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除这个账号吗？"
              @confirm="chgStatus(scope.row, 2)">
              <el-button type="text" slot="reference" size="small">删除</el-button>
            </el-popconfirm>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      :page-sizes="[10, 20, 40, 60, 80, 100]"
      :page-size="pageInfo.pageSize"
      :total="pageInfo.totalRecord"
      layout="prev, pager, next, sizes, total"
      style="margin-top:16px;">
    </el-pagination>
  </el-main>
</template>

<script>
  export default{
    data(){
      return {
        /* 是否加载状态 */
        loading: true,
        /* 是否显示弹出框 */
        dialogFormVisible: false,
        registInfo: {
          user: {
            roleIDs:[]
          },
          community: {},
          merchant: {},
          userView: false,  //业主
          merchantView: false, //商家
          propertyView: false,  //物业
          adminView: false
        },
        rules: {
          "user.username": [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          "user.password": [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          "user.nickname": [
            { required: true, message: '请输入昵称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          "user.phone": [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { type: 'number', message: '电话只能由数字组成'}
          ],
          "user.roleIDs": [
            { type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }
          ],
          "community.name": [
            { required: true, message: '请输入小区名字', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          "community.address": [
            { required: true, message: '请输入小区地址', trigger: 'blur' },
            { min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur' }
          ],
          "community.introduce": [
            { required: true, message: '请输入小区介绍', trigger: 'blur' },
            { min: 10, max: 200, message: '长度在 10 到 200 个字符', trigger: 'blur' }
          ],
          "community.helpPhone": [
            { required: true, message: '请输入管家电话', trigger: 'blur' },
            { type: 'number', message: '电话只能由数字组成'}
          ],
          "merchant.name": [
            { required: true, message: '请输入商家名称', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          "merchant.detail": [
            { required: true, message: '请输入商家介绍', trigger: 'blur' },
            { min: 10, max: 50, message: '长度在 10 到 50 个字符', trigger: 'blur' }
          ],
          "merchant.charter": [
            { required: true, message: '请上传营业执照', trigger: 'blur' },
          ],
        },
        /* 页面数据 */
        pageInfo: {
          currentPage: 1, //当前页面，默认1
          pageSize: 10, //页面大小，默认10
          totalRecord: 0, //总条数，默认0
        },
        /* 本地的user对象 */
        users:[],
        /* 选中行的user们 */
        selectUsers:[]
      }
    },
    methods: {
      /* 获取动态信息 */
      getPageInfo: function(){
        // 显示加载动画
        this.loading = true;

        /* 获取动态信息刚加载默认查询第一页、10个 */
        this.$axios.get("acct/get/" + this.pageInfo.currentPage +"/" + this.pageInfo.pageSize).then(res => {
          if(res.data.status == "SUCCESS"){
            //为每个user对象初始化一个roleIDs，以便打开分配角色的弹出窗时，可以正确存放已选择的角色
            for(let user of res.data.data.list){
              user.roleIDs = []
            }

            //保存数据
            this.pageInfo = res.data.data

            // 结束加载动画
            this.loading = false;
          }else{
            this.$message.error("获取数据失败")
          }
        })
      },
      checkUsername: function(){
         if(this.registInfo.user.username != "" && this.registInfo.user.username.length >= 3 && this.registInfo.user.username.length <=10){
          this.$axios.get("acct/checkUsername/" + this.registInfo.user.username).then(res => {
            if(res.data.status == "SUCCESS"){
              this.$message.success("该用户名可用")
            }else{
              this.$message.error("该用户名不可用")
            }
          })
        }
      },
      adminViewChg: function(value){
        this.registInfo.adminView = value
      },
      propertyViewChg: function(value){
        this.registInfo.propertyView = value
      },
      merchantViewChg: function(value){
        this.registInfo.merchantView = value
      },
      userViewChg: function(value){
        this.registInfo.userView = value
      },
      addUser: function(){
        //使用element ui自带的验证规则，如果未通过，返回不执行
        let flag = true;
        this.$refs['registInfo'].validate((valid) => {
          if (!valid) {
            flag = false;
          }
        });
        if(!flag){
          return;
        }

        // 手机号格式检查
        if(this.registInfo.user.phone.toString().length != 11){
          this.$message.error("请检查手机号格式后重试")
          return;
        }

        // 将选择的角色id们转换为角色对象存到roles中
        this.registInfo.user.roles = []
        for(let id of this.registInfo.user.roleIDs){
          this.registInfo.user.roles.push({"id": id})
        }

        this.$axios.post("acct/add", this.registInfo).then(res => {
          if(res.data.status == "SUCCESS"){
            this.pageInfo.list.push(res.data.data.user)
            //初始化注册信息
            this.registInfo = {user: {roleIDs:[] }, community: {}, merchant: {}, userView: false, merchantView: false, propertyView: false, adminView: false}
            //关闭添加窗口
            this.dialogFormVisible = false
            this.$message.success("添加成功")
          }else{
            this.$message.error("添加失败")
          }
        })

        //添加日志
        this.$axios.post("log/add", {target: "用户管理", type: "添加"})
      },
      handleRemove: function(){
        this.registInfo.merchant.charter = ""
      },
      handleSuccess: function(response){
        if(response.status == "SUCCESS"){
          /* 营业执照只能上传一张，只需要把返回数组的0索引赋值给商家营业执照信息 */
          this.$message.success("营业执照上传成功")
          this.registInfo.merchant.charter = response.data[0];
        }else{
          this.$message.error("文件上传失败，请重试")
        }
      },
      /* 分页插件当前页选择事件 */
      handleCurrentChange: function(currentPage){
        //同步选择的当前页面
        this.pageInfo.currentPage = currentPage;

        this.getPageInfo()
      },
      /* 分页插件页面大小更改事件 */
      handleSizeChange: function(pageSize){
        //同步选择的页面大小
        this.pageInfo.pageSize = pageSize;

        this.getPageInfo()
      },
      /* 表格全选事件，由于选中钩子不能响应全不选的情况，所以需要此钩子函数判断选中数量为0，清空值 */
      handleSelectAll: function(selection){
        if(selection.length == 0){
          this.selectUsers = []
        }
      },
      /* 被选中/取消的钩子，该钩子函数传递的是所有已选中的行数据 */
      handleSelectionChange: function(selection){
        this.selectUsers = selection
      },
      /* 角色过滤器触发事件 */
      filterRoleTag(value, row) {
        // 如果行中有角色id和筛选内容的value值（也是角色对应的id）一致，返回true
        let flag = false;
        for(let role of row.roles){
          if(role.id === value){
            flag = true
            break
          }
        }
        
        return flag;
      },
      /* 状态过滤器触发事件 */
      filterStatusTag(value, row) {
        // 如果行中的状态值和筛选内容的value值（也是状态值）一致，返回true
        return row.status === value
      },
      /* 开启/禁用的开关点击、恢复账号的点击事件 */
      chgStatus: function(user, status){
        this.$axios.put("http://localhost:8080/acct/chgStatus/" + user.id +"/" + status).then(res => {
          if(res.data.status == "SUCCESS"){
            user.status = status
          }else{
            //修改失败，将点击开关自动修改的值修正
            if(status == 0){
              user.status == 1
            }else{
              user.status == 0
            }
            this.$message.erro("账户状态修改失败")
          }
        })

        //添加日志
        this.$axios.post("log/add", {target: "用户管理", type: "修改状态"})
      },
      /* 批量修改状态 */
      batchChgStatus: function(status){
        let sum = this.selectUsers.length
        let success = 0
        let fail = 0
        for(let user of this.selectUsers){
          this.$axios.put("http://localhost:8080/acct/chgStatus/" + user.id +"/" + status).then(res => {
            if(res.data.status == "SUCCESS"){
              user.status = status
              success ++
            }else{
              fail ++
            }

            if((success + fail) == sum){
              this.$message(sum + " 个账户状态设置完成，成功 " + success + "个，失败 " + fail + "个")
            }
          })
        }

        //添加日志
        this.$axios.post("log/add", {target: "用户管理", type: "批量修改状态 " + this.selectUsers.length + "条"})
      },
      /* 判断pageInfo集合中user对象是否包含某个角色 */
      checkRole: function(roles, roleID){
        for(let role of roles){
          if(role.id == roleID){
            return true
          }
        }
        return false
      },
      chgRole: function(user, roleID){
        //如果对象中的角色已经有这个角色id，说明是需要取消该角色，反之是需要加该角色
        let r_index //如果角色已存在的话，记录角色的索引位置
        let has = false
        for(let i in user.roles){
          if(user.roles[i].id == roleID){
            r_index = i
            has = true
            break
          }
        }

        this.$axios.put("acct/chgRole/" + user.id + "/" + !has + "/" + roleID).then(res => {
          if(res.data.status == "SUCCESS"){
            if(has){
              //如果是减少该角色
              user.roles.splice(r_index, 1)
            }else{
              //如果是添加该角色
              user.roles.push({id: roleID})
            }
          }else{
            if(has){
              //如果是减少该角色失败了，把取消的角色id添加回记录选择的角色id们
              user.roleIDs.push(roleID)
            }else{
              //如果是添加该角色失败了，把添加的角色id从记录选择的角色id们删除
              user.roleIDs.splice(user.roleIDs.indexOf(roleID), 1)
            }
          }
        })

        //添加日志
        this.$axios.post("log/add", {target: "用户管理", type: "修改角色"})
      }
    },
    mounted(){
      // 获取页面信息
      this.getPageInfo()
    }
  }
</script>

<style scoped>

</style>
